package com.tanxi521.com.thenorthtitle.command;

import com.tanxi521.com.thenorthtitle.TheNorthTitle;
import com.tanxi521.com.thenorthtitle.entity.TheNorthTitleData;
import com.tanxi521.com.thenorthtitle.entity.TheNorthTitlePlayer;
import com.tanxi521.com.thenorthtitle.event.TnTitleListener;
import com.tanxi521.com.thenorthtitle.sql.dao.TnTitleBaseInfoMapper;
import com.tanxi521.com.thenorthtitle.util.GuiUtil;
import com.tanxi521.com.thenorthtitle.util.PageUtil;
import com.tanxi521.com.thenorthtitle.util.PointApi;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class TheNorthTitleCmd implements CommandExecutor, TabCompleter {

    public static final String PASSWORD = "Ilegame123WoCa";

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

        Player player = TheNorthTitle.getInstance().getServer().getPlayer(sender.getName());
        if (args.length == 0) return false;
        if (args[0].equalsIgnoreCase("openGui")) {
            return GuiUtil.openSelectGui((Player) sender);
        }

        if ((args.length == 1 && args[0].equals("help"))) {
            if (sender.isOp()) {
                sender.sendMessage("§2================[称号系统]================");
                sender.sendMessage("/tntitle me                       查看自己拥有的称号");
                sender.sendMessage("/tntitle add                       新增称号");
                sender.sendMessage("§2================[称号系统]================");
                return true;
            }
            sender.sendMessage("§2================[称号系统]================");
            sender.sendMessage("/tntitle me                       查看自己拥有的称号");
            sender.sendMessage("§2================[称号系统]================");
            return true;
        }
        if (args[0].equals("me")) {
            if (args.length == 1) PageUtil.topPage(1, sender);
            else {
                int currentPage = 1;
                try {
                    currentPage = Integer.parseInt(args[1]);
                } catch (Exception e) {
                    sender.sendMessage(ChatColor.RED + "§l指令错误,请查看/tntitle help");
                }
                PageUtil.topPage(currentPage, sender);
            }
            return true;
        }
        if (args.length == 2 && args[0].equals("set")) {
            int titleId = 1;
            try {
                titleId = Integer.parseInt(args[1]);
            } catch (Exception e) {
                sender.sendMessage(ChatColor.RED + "§l指令错误,请查看/tntitle help");
                return false;
            }
            if (TnTitleBaseInfoMapper.selectHas(sender.getName(), titleId) <= 0) {
                sender.sendMessage("你没有这个称号");
                return false;
            }
            TnTitleBaseInfoMapper.setTitle(sender, titleId);
            return true;
        }
        /**
         * /tntitle add name price discount relyon
         */
        if (args[0].equals("add")) {
            return addTitle(sender, args);
        }

        if (args[0].equals("give") && args.length == 3) {
            if (!player.isOp()) return false;
            int id;
            try {
                id = Integer.parseInt(args[2]);
            } catch (Exception e) {
                sender.sendMessage("称号只能填写称号id");
                return false;
            }

            OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[1]);
            if (null == offlinePlayer) {
                sender.sendMessage("玩家不存在");
                return false;
            }

            TheNorthTitlePlayer theNorthTitlePlayer = new TheNorthTitlePlayer();
            theNorthTitlePlayer.setTitleId(id).setPlayerName(offlinePlayer.getName())
                    .setAchieveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                    .setPlayerUuid(player.getUniqueId().toString());
            if (TnTitleBaseInfoMapper.giveTitle(theNorthTitlePlayer) <= 0) {
                sender.sendMessage("§c称号给予失败，请重试");
                return false;
            }
            sender.sendMessage("给予称号成功");
            return true;
        }

        return false;
    }

    private boolean addTitle(CommandSender sender, String[] args) {

        boolean isCustom = false;

        if (args.length == 7) isCustom = PASSWORD.equals(args[6]);

        if (!sender.isOp() && !isCustom) return false;

        if (args.length < 5) {
            sender.sendMessage("用法: /tntitle add 称号名 称号价格 商店购买折扣 前置称号");
            String[] tips = new String[]{
                    "§e§l参数说明",
                    "§a称号名: 任何名称(/sc查看颜色代码)",
                    "§a称号价格: 任何数字",
                    "§a商店购买折扣: 0-100数字",
                    "§a前置称号: 按tab补全输入"
            };
            sender.sendMessage(tips);

            return true;
        } else {
            try {

                if (isCustom) {
                    Player player = (Player) sender;
                    boolean point = PointApi.hasPoint(player, 1000);
                    if (!point) {
                        player.sendMessage("§c你的钻石不足");
                        TnTitleListener.customizingPlayer.remove(player.getName());
                        return false;
                    }
                }

                TheNorthTitleData titleData = new TheNorthTitleData();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String name = args[1].replaceAll("&", "§");
                double price = Double.parseDouble(args[2]);
                double discount = Double.parseDouble(args[3]) / 100;
                String titlePre = args[4];
                String relyOn = TnTitleBaseInfoMapper.selectId(titlePre);

                String playerName = sender.getName();

                if (relyOn.equals("妹有前置")) throw new SQLException();
                titleData.setTitleName(name)
                        .setTitlePrice(price)
                        .setTitleShopDiscount(discount)
                        .setTitleRelyOn(relyOn)
                        .setTitleRewardMul(1.0)
                        .setCreateBy(playerName)
                        .setCreateTime(simpleDateFormat.format(new Date()))
                        .setUpdateBy(playerName)
                        .setUpdateTime(simpleDateFormat.format(new Date()))
                        .setBelongTo(isCustom ? "public" : args[5]);
                if (TnTitleBaseInfoMapper.insertNewTitle(titleData) <= 0) throw new SQLException();
                sender.sendMessage((isCustom ? "§e专属定制称号 " : "§e新增称号 ") + titleData.getTitleName() + " §e成功");

                if (isCustom) {

                    String id = TnTitleBaseInfoMapper.selectId(name);
                    TheNorthTitlePlayer theNorthTitlePlayer = new TheNorthTitlePlayer();
                    Player player = (Player) sender;
                    PointApi.takePoints(player, 1000);
                    theNorthTitlePlayer.setTitleId(Integer.parseInt(id)).setPlayerName(playerName)
                            .setAchieveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                            .setPlayerUuid(player.getUniqueId().toString());
                    if (TnTitleBaseInfoMapper.giveTitle(theNorthTitlePlayer) <= 0) {
                        sender.sendMessage("§c称号给予失败，请截图联系管理员");
                        TnTitleListener.customizingPlayer.remove(player.getName());
                        return false;
                    }
                    TnTitleListener.customizingPlayer.remove(player.getName());
                }

                TheNorthTitle.allTitleName = TnTitleBaseInfoMapper.selectAll();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                TheNorthTitle.getInstance().getLogger().info("新建称号错误");
                sender.sendMessage("§c参数错误或前置称号不存在，请检查后重试");
                return false;
            }
        }
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
        if (args.length == 5)
            return TheNorthTitle.allTitleName.stream().filter(s -> s.contains(args[4])).collect(Collectors.toList());
        return null;
    }
}
